package com.bs.service;


import com.bs.domain.SvcExecuteInfo;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.LongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsBuilder;
import org.elasticsearch.search.aggregations.metrics.stats.extended.InternalExtendedStats;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class SvcAnalysisService {

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;
    private String partition;
    private long pid;
    private String startTime;
    private String endTime;


    private SearchResponse getResponse() {
        Client transportClient = elasticsearchTemplate.getClient();
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.matchPhrasePrefixQuery("logmsg", "4. service end."));
        builder.filter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("partition", partition))
            .must(QueryBuilders.termQuery("pid", pid))
            .must(QueryBuilders.rangeQuery("@timestamp").from(startTime).to(endTime).timeZone("+08:00")));
        SearchRequestBuilder searchRequestBuilder = transportClient.prepareSearch("logstash-*-svcsql-*").setTypes("log");
        TermsBuilder svcAgg = AggregationBuilders.terms("services").field("svc")
            .size(30)
            .order(Terms.Order.aggregation("svr_exec_time", "std_deviation", false));
        ExtendedStatsBuilder extAgg = AggregationBuilders.extendedStats("svr_exec_time").field("exec_time");
        return searchRequestBuilder
            .setSize(0)
            .setQuery(builder)
            .addAggregation(svcAgg.subAggregation(extAgg))
            .execute().actionGet();
    }

    public List<SvcExecuteInfo> getSvcList(String partition, long pid, String startTime, String endTime) {
        this.partition = partition;
        this.pid = pid;
        this.startTime = startTime;
        this.endTime = endTime;
        List<SvcExecuteInfo> svcExecuteInfoList = new ArrayList<>();
        SearchResponse response = getResponse();
        StringTerms svcAgg = (StringTerms) response.getAggregations().asMap().get("services");
        Iterator<Terms.Bucket> svcBucket = svcAgg.getBuckets().iterator();
        while (svcBucket.hasNext()) {
            Terms.Bucket buck = svcBucket.next();
            String service = buck.getKeyAsString();
            long count = buck.getDocCount();
            InternalExtendedStats internalExtendedStats = (InternalExtendedStats) buck.getAggregations().asMap().get("svr_exec_time");
            double min = internalExtendedStats.getMin();
            double max = internalExtendedStats.getMax();
            double avg = internalExtendedStats.getAvg();
            double std_deviation = internalExtendedStats.getStdDeviation();
            SvcExecuteInfo svcExecuteInfo = new SvcExecuteInfo(service, count, min, max, avg, std_deviation);
            svcExecuteInfoList.add(svcExecuteInfo);
        }
        return svcExecuteInfoList;

    }

}
